package com.hzhr.iot.cqgas.ds.schedule;

import com.hzhr.iot.core.constant.CommonOptions;
import com.hzhr.iot.core.util.HzhrDateUtil;
import com.hzhr.iot.core.util.HzhrTypeUtil;
import com.hzhr.iot.cqgas.ds.dao.device.custom.DevCollectDataCustomDao;
import com.hzhr.iot.cqgas.ds.dao.device.custom.DevCollectDeviceCustomDao;
import com.hzhr.iot.cqgas.ds.dao.device.custom.DeviceDao;
import com.hzhr.iot.cqgas.ds.dao.device.example.*;
import com.hzhr.iot.cqgas.ds.dao.log.LogDao;
import com.hzhr.iot.cqgas.ds.dao.smartmeter.custom.SmCollectDataCustomDao;
import com.hzhr.iot.cqgas.ds.dao.smartmeter.custom.SmDao;
import com.hzhr.iot.cqgas.ds.dao.smartmeter.custom.SmDeviceCustomDao;
import com.hzhr.iot.cqgas.ds.dao.smartmeter.custom.SmGasUserCustomDao;
import com.hzhr.iot.cqgas.ds.dao.smartmeter.example.SmMeterDao;
import com.hzhr.iot.cqgas.ds.dao.smartmeter.example.SmNodeNetworkDao;
import com.hzhr.iot.cqgas.ds.dao.statis.custom.StatisDao;
import com.hzhr.iot.cqgas.ds.dao.toll.custom.TollGasUserCustomDao;
import com.hzhr.iot.cqgas.ds.dao.toll.example.TollGasUserDao;
import com.hzhr.iot.cqgas.ds.dao.user.custom.UserCustomDao;
import com.hzhr.iot.cqgas.ds.dao.user.example.UsrCompanyDao;
import com.hzhr.iot.cqgas.ds.dao.user.example.UsrDeptDao;
import com.hzhr.iot.cqgas.ds.dao.user.example.UsrUserDao;
import com.hzhr.iot.cqgas.ds.dao.user.example.UsrUserInRoleDao;
import com.hzhr.iot.cqgas.ds.entity.custom.CustomEntity1;
import com.hzhr.iot.cqgas.ds.entity.device.*;
import com.hzhr.iot.cqgas.ds.entity.device.dto.DevCollectDeviceEntityDto;
import com.hzhr.iot.cqgas.ds.entity.smartmeter.NbMeterEntity;
import com.hzhr.iot.cqgas.ds.entity.toll.TollGasUserEntity;
import com.hzhr.iot.cqgas.ds.entity.toll.TollGasUserExample;
import com.hzhr.iot.cqgas.ds.entity.toll.dto.TollGasUserEntityDto;
import com.hzhr.iot.cqgas.ds.entity.user.*;
import com.hzhr.iot.cqgas.ds.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.*;
import java.util.concurrent.Future;

@Component
public class SyncSchedule {
    @Autowired
    CollectingDataService collectingDataService;
    @Autowired
    DevIotDeviceDao devIotDeviceDao;
    @Autowired
    DevCollectDeviceDao devCollectDeviceDao;
    @Autowired
    StatisService statisService;
    @Autowired
    TollGasUserDao tollGasUserDao;
    @Autowired
    UsrDeptDao usrDeptDao;
    @Autowired
    CompanyService companyService;
    @Autowired
    UsrCompanyDao usrCompanyDao;
    @Autowired
    ProdFactoryService prodFactoryService;
    @Autowired
    DevProdFactoryDao devProdFactoryDao;
    @Autowired
    DeptService deptService;
    @Autowired
    CollectDeviceTypeService collectDeviceTypeService;
    @Autowired
    DevCollectDeviceTypeDao devCollectDeviceTypeDao;
    @Autowired
    IotDeviceTypeService iotDeviceTypeService;
    @Autowired
    DevIotDeviceTypeDao devIotDeviceTypeDao;
    @Autowired
    GasUserService gasUserService;
    @Autowired
    UserService userService;
    @Autowired
    UsrUserDao usrUserDao;
    @Autowired
    IotDeviceService iotDeviceService;
    @Autowired
    CollectDeviceService collectDeviceService;
    @Autowired
    SmDeviceCustomDao smDeviceCustomDao;
    @Autowired
    SmMeterDao smMeterDao;
    @Autowired
    SmNodeNetworkDao smNodeNetworkDao;
    @Autowired DevOptionsService devOptionsService;
    @Autowired
    SmCollectDataCustomDao smCollectDataCustomDao;
    @Autowired
    DevCollectDataDao devCollectDataDao;
    @Autowired
    DevCollectDataCustomDao devCollectDataCustomDao;
    @Autowired
    SmGasUserCustomDao smGasUserCustomDao;
    @Autowired
    TollOptionsService tollOptionsService;
    @Autowired
    StatisDao statisDao;
    @Autowired
    UsrUserInRoleDao usrUserInRoleDao;
    @Autowired
    DevCollectDeviceCustomDao devCollectDeviceCustomDao;
    @Autowired
    UserCustomDao userCustomDao;
    @Autowired
    DeviceDao deviceDao;
    @Autowired
    LogDao logDao;
    @Autowired
    SmDao smDao;
    @Autowired
    TollGasUserCustomDao tollGasUserCustomDao;
    @Autowired
    DevImplRecordDao devImplRecordDao;

    private Logger logger = LoggerFactory.getLogger(SyncSchedule.class);

    @Value("${spring.profiles.active}")
    String active;
    @Value("${companyId}")
    String companyId;

    @Scheduled(cron = "0 30 * * * ?")
    @Async
    public void syncCollectingData_day() throws Exception {
        if ("dev".equals(this.active)) return;
        int syncCount = 0;
        long start = new Date().getTime();

        Date date1 = HzhrDateUtil.addDay(new Date(), -1);
        Date date2 = new Date();

        //查询出采集设备
        List<DevCollectDeviceEntity> devCollectDeviceEntities = devCollectDeviceDao.selectByExample(null);
        Map<String, Integer> collectDevices = new HashMap<>();
        for (DevCollectDeviceEntity devCollectDeviceEntity :
                devCollectDeviceEntities) {
            collectDevices.put(devCollectDeviceEntity.getOutId(), devCollectDeviceEntity.getId());
        }
        //查询出物联网设备
        List<DevIotDeviceEntity> devIotDeviceEntities = devIotDeviceDao.selectByExample(null);
        Map<String, Integer> iotDevices = new HashMap<>();
        for (DevIotDeviceEntity devIotDeviceEntity :
                devIotDeviceEntities) {
            iotDevices.put(devIotDeviceEntity.getOutId(), devIotDeviceEntity.getId());
        }

        //同步数据
        List<Future<Integer>> lstFuture = new ArrayList<Future<Integer>>();// 存放所有的线程，用于获取结果
        for (int i = 1; i <= 10; i++) {
            Future<Integer> result = collectingDataService.syncCollectingData(i, date1, date2, collectDevices, iotDevices);
            lstFuture.add(result);
        }
        for (Future<Integer> future : lstFuture) {// 获取值。get是阻塞式，等待当前线程完成才返回值
            syncCount += future.get();
        }

        long end = new Date().getTime();
        logger.info("同步采集数据结束: " + (end - start) / 1000 + "s");
        logger.info("同步时间: " + (end - start) / 1000 + "s");
        logger.info("同步数量: " + syncCount + "条");
    }

    @Scheduled(cron = "0 0 0 * * ?")
    @Async
    public void syncCompany() {
        if ("dev".equals(this.active)) return;
        UsrCompanyEntity usrCompanyEntity = new UsrCompanyEntity();
        usrCompanyEntity.setState("3");
        UsrCompanyExample usrCompanyExample = new UsrCompanyExample();
        usrCompanyExample.createCriteria().andOutIdIsNotNull();
        usrCompanyDao.updateByExampleSelective(usrCompanyEntity, usrCompanyExample);

        companyService.syncIotCompany();

        usrCompanyExample = new UsrCompanyExample();
        usrCompanyExample.createCriteria().andStateEqualTo("3");
        usrCompanyDao.deleteByExample(usrCompanyExample);
    }

    @Scheduled(cron = "0 30 0 * * ?")
    @Async
    public void syncProdFactory() {
        if ("dev".equals(this.active)) return;
        DevProdFactoryEntity devProdFactoryEntity = new DevProdFactoryEntity();
        devProdFactoryEntity.setState("3");
        DevProdFactoryExample devProdFactoryExample = new DevProdFactoryExample();
        devProdFactoryExample.createCriteria().andOutIdIsNotNull();
        devProdFactoryDao.updateByExampleSelective(devProdFactoryEntity, devProdFactoryExample);

        prodFactoryService.syncProdFactory();

        devProdFactoryExample = new DevProdFactoryExample();
        devProdFactoryExample.createCriteria().andStateEqualTo("3");
        devProdFactoryDao.deleteByExample(devProdFactoryExample);
    }
    @Scheduled(cron = "0 30 0 * * ?")
    @Async
    public void syncDept() {
        if ("dev".equals(this.active)) return;
        UsrDeptEntity usrDeptEntity = new UsrDeptEntity();
        usrDeptEntity.setState("3");
        UsrDeptExample usrDeptExample = new UsrDeptExample();
        usrDeptExample.createCriteria().andOutIdIsNotNull();
        usrDeptDao.updateByExampleSelective(usrDeptEntity, usrDeptExample);

        deptService.syncDept();

        usrDeptExample = new UsrDeptExample();
        usrDeptExample.createCriteria().andStateEqualTo("3");
        usrDeptDao.deleteByExample(usrDeptExample);
    }


    @Scheduled(cron = "0 0 1 * * ?")
    @Async
    public void syncCollectDeviceType() {
        if ("dev".equals(this.active)) return;
        DevCollectDeviceTypeEntity devCollectDeviceTypeEntity = new DevCollectDeviceTypeEntity();
        devCollectDeviceTypeEntity.setState("3");
        DevCollectDeviceTypeExample devCollectDeviceTypeExample = new DevCollectDeviceTypeExample();
        devCollectDeviceTypeExample.createCriteria().andOutIdIsNotNull();
        devCollectDeviceTypeDao.updateByExampleSelective(devCollectDeviceTypeEntity, devCollectDeviceTypeExample);

        collectDeviceTypeService.syncCollectDeviceType();

        devCollectDeviceTypeExample = new DevCollectDeviceTypeExample();
        devCollectDeviceTypeExample.createCriteria().andStateEqualTo("3");
        devCollectDeviceTypeDao.deleteByExample(devCollectDeviceTypeExample);
    }
    @Scheduled(cron = "0 0 1 * * ?")
    @Async
    public void syncIotDeviceType() {
        if ("dev".equals(this.active)) return;
        DevIotDeviceTypeEntity devIotDeviceTypeEntity = new DevIotDeviceTypeEntity();
        devIotDeviceTypeEntity.setState("3");
        DevIotDeviceTypeExample devIotDeviceTypeExample = new DevIotDeviceTypeExample();
        devIotDeviceTypeExample.createCriteria().andOutIdIsNotNull();
        devIotDeviceTypeDao.updateByExampleSelective(devIotDeviceTypeEntity, devIotDeviceTypeExample);

        iotDeviceTypeService.syncIotDeviceType();

        devIotDeviceTypeExample = new DevIotDeviceTypeExample();
        devIotDeviceTypeExample.createCriteria().andStateEqualTo("3");
        devIotDeviceTypeDao.deleteByExample(devIotDeviceTypeExample);
    }
    @Scheduled(cron = "0 0 1 * * ?")
    @Async
    public void syncGasUser() {
        if ("dev".equals(this.active)) return;
        TollGasUserEntity tollGasUserEntity = new TollGasUserEntity();
        tollGasUserEntity.setState("3");
        TollGasUserExample tollGasUserExample = new TollGasUserExample();
        tollGasUserExample.createCriteria().andOutIdIsNotNull();
        tollGasUserDao.updateByExampleSelective(tollGasUserEntity, tollGasUserExample);

        gasUserService.syncGasUser(null, null);

        tollGasUserExample = new TollGasUserExample();
        tollGasUserExample.createCriteria().andStateEqualTo("3");
        tollGasUserDao.deleteByExample(tollGasUserExample);
    }
    @Scheduled(cron = "0 0 1 * * ?")
    @Async
    public void syncUser() {
        if ("dev".equals(this.active)) return;
        UsrUserEntity usrUserEntity = new UsrUserEntity();
        usrUserEntity.setState("3");
        UsrUserExample usrUserExample = new UsrUserExample();
        usrUserExample.createCriteria().andOutIdIsNotNull();
        usrUserDao.updateByExampleSelective(usrUserEntity, usrUserExample);

        userService.syncUser();

        usrUserExample = new UsrUserExample();
        usrUserExample.createCriteria().andStateEqualTo("3");
        usrUserDao.deleteByExample(usrUserExample);
    }
    @Scheduled(cron = "0 0 1 * * ?")
    @Async
    public void syncIotDevice() {
        if ("dev".equals(this.active)) return;
        DevIotDeviceEntity devIotDeviceEntity = new DevIotDeviceEntity();
        devIotDeviceEntity.setState("3");
        DevIotDeviceExample devIotDeviceExample = new DevIotDeviceExample();
        devIotDeviceExample.createCriteria().andOutIdIsNotNull();
        devIotDeviceDao.updateByExampleSelective(devIotDeviceEntity, devIotDeviceExample);

        iotDeviceService.syncIotDevice(null, null);

        devIotDeviceExample = new DevIotDeviceExample();
        devIotDeviceExample.createCriteria().andStateEqualTo("3");
        devIotDeviceDao.deleteByExample(devIotDeviceExample);
    }

    @Scheduled(cron = "0 0 2 * * ?")
    @Async
    public void syncUserInRole() {
        if ("dev".equals(this.active)) return;
        UsrUserExample usrUserExample = new UsrUserExample();
        usrUserExample.createCriteria().andOutIdIsNotNull();
        List<UsrUserEntity> usrUserEntities = this.usrUserDao.selectByExample(usrUserExample);

        Iterator iterator = usrUserEntities.iterator(); while (iterator.hasNext()) { UsrUserEntity usrUserEntity = (UsrUserEntity)iterator.next();
            UsrUserInRoleExample example = new UsrUserInRoleExample();
            example.createCriteria().andUserIdEqualTo(usrUserEntity.getId());
            List<UsrUserInRoleEntity> usrUserInRoleEntities = this.usrUserInRoleDao.selectByExample(example);
            if (usrUserInRoleEntities.size() == 0) {
                UsrUserInRoleEntity usrUserInRoleEntity = new UsrUserInRoleEntity();
                usrUserInRoleEntity.setUserId(usrUserEntity.getId());
                usrUserInRoleEntity.setRoleId(Integer.valueOf(2));
                this.usrUserInRoleDao.insert(usrUserInRoleEntity);
            }  }

    }

    @Scheduled(cron = "0 0 4 * * ?")
    @Async
    public void syncCollectDevice() {
        if ("dev".equals(this.active)) return;
        DevCollectDeviceEntity devCollectDeviceEntity = new DevCollectDeviceEntity();
        devCollectDeviceEntity.setState("3");
        DevCollectDeviceExample devCollectDeviceExample = new DevCollectDeviceExample();
        devCollectDeviceExample.createCriteria().andOutIdIsNotNull().andCategoryCodeNotEqualTo("7").andCategoryCodeNotEqualTo("8");
        devCollectDeviceDao.updateByExampleSelective(devCollectDeviceEntity, devCollectDeviceExample);

        collectDeviceService.syncCollectDevice(null, null);

        devCollectDeviceExample = new DevCollectDeviceExample();
        devCollectDeviceExample.createCriteria().andOutIdIsNotNull().andCategoryCodeNotEqualTo("7").andCategoryCodeNotEqualTo("8").andStateEqualTo("3");
        devCollectDeviceDao.deleteByExample(devCollectDeviceExample);
    }
    @Scheduled(cron = "0 0 4 * * ?")
    @Async
    public void syncRegulatorDevice() {
        if ("dev".equals(this.active)) return;
        DevCollectDeviceEntity devCollectDeviceEntity = new DevCollectDeviceEntity();
        devCollectDeviceEntity.setState("3");
        DevCollectDeviceExample example = new DevCollectDeviceExample();
        List<String> categoryCodes = new ArrayList<>();
        categoryCodes.add("7");
        categoryCodes.add("8");
        example.createCriteria().andOutIdIsNotNull().andCategoryCodeIn(categoryCodes);
        devCollectDeviceDao.updateByExampleSelective(devCollectDeviceEntity, example);

        collectDeviceService.syncRegulatorDevice();

        example = new DevCollectDeviceExample();
        example.createCriteria().andStateEqualTo("3").andOutIdIsNotNull().andCategoryCodeIn(categoryCodes);
        devCollectDeviceDao.deleteByExample(example);
    }
    //同步自建的lora表
    @Scheduled(cron = "0 0 4 * * ?")
    @Async
    public void syncLoraMeter() {
        if ("dev".equals(this.active)) return;
        int addCount = 0;
        int updateCount = 0;
        long startTime = new Date().getTime();

        String resident = tollOptionsService.getCode("GAS_USER_TYPE", "RESIDENTIAL_USER");
        String commercial = tollOptionsService.getCode("GAS_USER_TYPE", "COMMERCIAL_USER");

        int i = 0;
        while (true) {
            Integer count = 5000;
            Integer start =  i * count;

            //查询平台自建的lora表的代码
            List<String> codes = deviceDao.select14(start, count);
            for (String code :
                    codes) {
                try {
                    //根据平台自建的lora表的代码找到这些表的营销系统信息
                    Map<String, Object> loraMeter = smDao.select3(code);
                    if (loraMeter != null) {
                        String ORG_ID = HzhrTypeUtil.object2string(loraMeter.get("ORG_ID"));
                        String YQDZ_YQZH = HzhrTypeUtil.object2string(loraMeter.get("YQDZ_YQZH"));
                        String YQDZ_HZ_MC = HzhrTypeUtil.object2string(loraMeter.get("YQDZ_HZ_MC"));
                        String YQDZ_SM = HzhrTypeUtil.object2string(loraMeter.get("YQDZ_SM"));
                        String yqdzKhLx = HzhrTypeUtil.object2string(loraMeter.get("YQDZ_KH_LX"));

                        //根据orgId找到部门
                        String deptCode = ORG_ID.replaceFirst("0000", "9-01");
                        Map<String, Object> dept = userCustomDao.select7(deptCode);
                        if (dept == null) continue;

                        //根据yqdzYqzh找到燃气用户编号，如果过找不到燃气用户则自建燃气用户
                        Integer gasUserId = tollGasUserCustomDao.select3(YQDZ_YQZH);
                        if (gasUserId == null) {
                            TollGasUserEntity tollGasUserEntity = new TollGasUserEntity();
                            tollGasUserEntity.setCode(YQDZ_YQZH);
                            tollGasUserEntity.setName(YQDZ_HZ_MC != null ? YQDZ_HZ_MC : "未知");
                            tollGasUserEntity.setAddress(YQDZ_SM);
                            if ("1".equals(yqdzKhLx)) {
                                tollGasUserEntity.setTypeCode(commercial);
                            } else if ("2".equals(yqdzKhLx)) {
                                tollGasUserEntity.setTypeCode(resident);
                            } else {
                                tollGasUserEntity.setTypeCode("0");
                            }
                            tollGasUserEntity.setCompanyId(Integer.parseInt(companyId));
                            tollGasUserEntity.setDeptId(HzhrTypeUtil.object2integer(dept.get("ID")));
                            tollGasUserEntity.setCreateTime(new Date());
                            tollGasUserEntity.setCreateUserId(0);
                            tollGasUserEntity.setResourceCode(HzhrTypeUtil.object2string(dept.get("RESOURCE_CODE")));
                            tollGasUserEntity.setIsValid(CommonOptions.YES_NO.YES);
                            tollGasUserEntity.setState("1");
                            tollGasUserDao.insert(tollGasUserEntity);

                            gasUserId = tollGasUserEntity.getId();
                        }

                        //根据营销系统信息更新这些lora表
                        DevCollectDeviceEntity devCollectDeviceEntity = new DevCollectDeviceEntity();
                        devCollectDeviceEntity.setCompanyId(9);
                        devCollectDeviceEntity.setDeptId(HzhrTypeUtil.object2integer(dept.get("ID")));
                        devCollectDeviceEntity.setDeptCode(deptCode);
                        devCollectDeviceEntity.setResourceCode(HzhrTypeUtil.object2string(dept.get("RESOURCE_CODE")));
                        devCollectDeviceEntity.setGasUserId(gasUserId);
                        devCollectDeviceEntity.setGasUserName(YQDZ_HZ_MC);
                        devCollectDeviceEntity.setGasUserCode(YQDZ_YQZH);
                        devCollectDeviceEntity.setGasUserAddress(YQDZ_SM);
                        devCollectDeviceEntity.setUpdateUserId(0);
                        devCollectDeviceEntity.setUpdateTime(new Date());
                        DevCollectDeviceExample devCollectDeviceExample = new DevCollectDeviceExample();
                        devCollectDeviceExample.createCriteria().andCodeEqualTo(code).andIsValidEqualTo("1");
                        devCollectDeviceDao.updateByExampleSelective(devCollectDeviceEntity, devCollectDeviceExample);
                        updateCount++;
                    }
                } catch (Throwable e) {
                    logger.error("同步lora表信息异常", e);
                }
            }

            if (codes.size() < 5000) {
                break;
            }

            i++;
        }

        long endTime = new Date().getTime();
        logger.info("更新自建lora表信息结束: " + (endTime - startTime) / 1000 + "s");
        logger.info("同步时间: " + (endTime - startTime) / 1000 + "s");
        logger.info("更新数量: " + updateCount + "条");
    }
    //同步自建的nb表
    @Scheduled(cron = "0 0 4 * * ?")
    @Async
    public void syncNbMeter() {
        int addCount = 0;
        int updateCount = 0;
        long startTime = new Date().getTime();

        String resident = tollOptionsService.getCode("GAS_USER_TYPE", "RESIDENTIAL_USER");
        String commercial = tollOptionsService.getCode("GAS_USER_TYPE", "COMMERCIAL_USER");

        //查询出采集设备类型
        List<DevCollectDeviceTypeEntity> devCollectDeviceTypeEntities = devCollectDeviceTypeDao.selectByExample(null);
        Map<String, Integer> collectDeviceTypes = new HashMap<>();
        for (DevCollectDeviceTypeEntity devCollectDeviceTypeEntity :
                devCollectDeviceTypeEntities) {
            collectDeviceTypes.put(devCollectDeviceTypeEntity.getOutId(), devCollectDeviceTypeEntity.getId());
        }

        int i = 0;
        while (true) {
            Integer count = 5000;
            Integer start =  i * count;

            //查询平台自建的nb表的代码
            List<Map<String, Object>> iotDevices = deviceDao.select16(start, count);
            for (Map<String, Object> iotDevice :
                    iotDevices) {
                String code = HzhrTypeUtil.object2string(iotDevice.get("CODE"));
                Integer id = HzhrTypeUtil.object2integer(iotDevice.get("ID"));

                try {
                    //根据平台自建的nb表的代码找到这些表的营销系统信息
                    NbMeterEntity nbMeter = smDao.select4(code);
                    if (nbMeter != null) {
                        String ORG_ID = nbMeter.getOrgId();
                        String YQDZ_YQZH = nbMeter.getYqdzYqzh();
                        String YQDZ_HZ_MC = nbMeter.getYqdzHzMc();
                        String YQDZ_SM = nbMeter.getYqdzSm();
                        String yqdzKhLx = nbMeter.getYqdzKhLx();
                        String mtId = nbMeter.getMtId();
                        String mtModel = nbMeter.getMtModel();
                        String rqbKssyrq = nbMeter.getRqbKssyrq();


                        //根据orgId找到部门
                        String deptCode = ORG_ID.replaceFirst("0000", "9-01");
                        Map<String, Object> dept = userCustomDao.select7(deptCode);
                        if (dept == null) continue;

                        //根据yqdzYqzh找到燃气用户编号，如果过找不到燃气用户则自建燃气用户

                        Integer gasUserId = tollGasUserCustomDao.select3(YQDZ_YQZH);
                        if (gasUserId == null) {
                            TollGasUserEntity tollGasUserEntity = new TollGasUserEntity();
                            tollGasUserEntity.setCode(YQDZ_YQZH);
                            tollGasUserEntity.setName(YQDZ_HZ_MC != null ? YQDZ_HZ_MC : "未知");
                            tollGasUserEntity.setAddress(YQDZ_SM);
                            if ("1".equals(yqdzKhLx)) {
                                tollGasUserEntity.setTypeCode(commercial);
                            } else if ("2".equals(yqdzKhLx)) {
                                tollGasUserEntity.setTypeCode(resident);
                            } else {
                                tollGasUserEntity.setTypeCode("0");
                            }
                            tollGasUserEntity.setCompanyId(Integer.parseInt(companyId));
                            tollGasUserEntity.setDeptId(HzhrTypeUtil.object2integer(dept.get("ID")));
                            tollGasUserEntity.setCreateTime(new Date());
                            tollGasUserEntity.setCreateUserId(0);
                            tollGasUserEntity.setResourceCode(HzhrTypeUtil.object2string(dept.get("RESOURCE_CODE")));
                            tollGasUserEntity.setIsValid(CommonOptions.YES_NO.YES);
                            tollGasUserEntity.setState("1");
                            tollGasUserDao.insert(tollGasUserEntity);

                            gasUserId = tollGasUserEntity.getId();
                        } else {
                            TollGasUserEntity tollGasUserEntity = new TollGasUserEntity();
                            tollGasUserEntity.setCode(YQDZ_YQZH);
                            tollGasUserEntity.setName(YQDZ_HZ_MC != null ? YQDZ_HZ_MC : "未知");
                            tollGasUserEntity.setAddress(YQDZ_SM);
                            if ("1".equals(yqdzKhLx)) {
                                tollGasUserEntity.setTypeCode(commercial);
                            } else if ("2".equals(yqdzKhLx)) {
                                tollGasUserEntity.setTypeCode(resident);
                            } else {
                                tollGasUserEntity.setTypeCode("0");
                            }
                            tollGasUserEntity.setCompanyId(Integer.parseInt(companyId));
                            tollGasUserEntity.setDeptId(HzhrTypeUtil.object2integer(dept.get("ID")));
                            tollGasUserEntity.setUpdateTime(new Date());
                            tollGasUserEntity.setUpdateUserId(0);
                            tollGasUserEntity.setResourceCode(HzhrTypeUtil.object2string(dept.get("RESOURCE_CODE")));

                            TollGasUserExample tollGasUserExample = new TollGasUserExample();
                            tollGasUserExample.createCriteria().andIdEqualTo(gasUserId);
                            tollGasUserDao.updateByExampleSelective(tollGasUserEntity, tollGasUserExample);
                        }

                        //根据营销系统信息创建或更新nb表的采集设备台账
                        DevCollectDeviceExample devCollectDeviceExample = new DevCollectDeviceExample();
                        devCollectDeviceExample.createCriteria().andCodeEqualTo(code).andCategoryCodeEqualTo("1").andIsValidEqualTo("1");
                        List<DevCollectDeviceEntity> collectDevices = devCollectDeviceDao.selectByExample(devCollectDeviceExample);
                        if (collectDevices.size() > 0) {
                            DevCollectDeviceEntity devCollectDeviceEntity = collectDevices.get(0);

                            Integer typeId = collectDeviceTypes.get(mtId);
                            if (typeId != null) {
                                devCollectDeviceEntity.setTypeId(typeId);
                            } else {
                                devCollectDeviceEntity.setTypeId(0);
                            }

                            devCollectDeviceEntity.setDes(mtModel);
                            devCollectDeviceEntity.setIotDeviceId(id);

                            devCollectDeviceEntity.setCompanyId(9);
                            devCollectDeviceEntity.setDeptId(HzhrTypeUtil.object2integer(dept.get("ID")));
                            devCollectDeviceEntity.setDeptCode(deptCode);
                            devCollectDeviceEntity.setResourceCode(HzhrTypeUtil.object2string(dept.get("RESOURCE_CODE")));
                            devCollectDeviceEntity.setGasUserId(gasUserId);
                            devCollectDeviceEntity.setGasUserName(YQDZ_HZ_MC);
                            devCollectDeviceEntity.setGasUserCode(YQDZ_YQZH);
                            devCollectDeviceEntity.setGasUserAddress(YQDZ_SM);
                            devCollectDeviceEntity.setInstallAddress(YQDZ_SM);
                            devCollectDeviceEntity.setUpdateUserId(0);
                            devCollectDeviceEntity.setUpdateTime(new Date());
                            devCollectDeviceDao.updateByPrimaryKey(devCollectDeviceEntity);
                            updateCount++;
                        } else {
                            DevCollectDeviceEntity devCollectDeviceEntity = new DevCollectDeviceEntity();
                            devCollectDeviceEntity.setCode(code);
                            devCollectDeviceEntity.setCategoryCode("1");

                            Integer typeId = collectDeviceTypes.get(mtId);
                            if (typeId != null) {
                                devCollectDeviceEntity.setTypeId(typeId);
                            } else {
                                devCollectDeviceEntity.setTypeId(0);
                            }

                            devCollectDeviceEntity.setDes(mtModel);
                            devCollectDeviceEntity.setIotDeviceId(id);
                            devCollectDeviceEntity.setCompanyId(9);
                            devCollectDeviceEntity.setDeptId(HzhrTypeUtil.object2integer(dept.get("ID")));
                            devCollectDeviceEntity.setDeptCode(deptCode);
                            devCollectDeviceEntity.setResourceCode(HzhrTypeUtil.object2string(dept.get("RESOURCE_CODE")));
                            devCollectDeviceEntity.setGasUserId(gasUserId);
                            devCollectDeviceEntity.setGasUserName(YQDZ_HZ_MC);
                            devCollectDeviceEntity.setGasUserCode(YQDZ_YQZH);
                            devCollectDeviceEntity.setGasUserAddress(YQDZ_SM);
                            devCollectDeviceEntity.setInstallAddress(YQDZ_SM);
                            devCollectDeviceEntity.setCreateUserId(0);
                            devCollectDeviceEntity.setCreateTime(new Date());
                            if (!StringUtils.isEmpty(rqbKssyrq)) {
                                devCollectDeviceEntity.setInstallTime(HzhrDateUtil.strToDate(rqbKssyrq));
                            }
                            devCollectDeviceEntity.setIsValid("1");
                            devCollectDeviceEntity.setState("1");
                            devCollectDeviceDao.insert(devCollectDeviceEntity);

                            addCount++;
                        }


                    }
                } catch (Throwable e) {
                    logger.error("同步nb表信息异常", e);
                }
            }

            if (iotDevices.size() < 5000) {
                break;
            }

            i++;
        }

        long endTime = new Date().getTime();
        logger.info("更新自建nb表信息结束: " + (endTime - startTime) / 1000 + "s");
        logger.info("同步时间: " + (endTime - startTime) / 1000 + "s");
        logger.info("更新数量: " + updateCount + "条");
        logger.info("新增数量: " + addCount + "条");

    }

    @Scheduled(cron = "0 30 4 * * ?")
    @Async
    public void syncImplResourceImg() {
        if ("dev".equals(this.active)) return;
        List<DevImplRecordEntity> devImplRecordEntities = devImplRecordDao.selectByExample(null);
        for (DevImplRecordEntity devImplRecordEntity :
                devImplRecordEntities) {
            boolean updateflag = false;
            //关联设备
            String iotDeviceCode = devImplRecordEntity.getIotDeviceCode();
            if (iotDeviceCode != null) {
                Integer iotDeviceId = deviceDao.select10(iotDeviceCode);
                if ((iotDeviceId == null && devImplRecordEntity.getIotDeviceId() != null) || (iotDeviceId != null && !iotDeviceId.equals(devImplRecordEntity.getIotDeviceId()))) {
                    devImplRecordEntity.setIotDeviceId(iotDeviceId);
                    updateflag = true;
                }

            }
            String collectDeviceCode = devImplRecordEntity.getCollectDeviceCode();
            if (collectDeviceCode != null) {
                Integer collectDeviceId = deviceDao.select11(collectDeviceCode);
                if ((collectDeviceId == null && devImplRecordEntity.getCollectDeviceId() != null) || (collectDeviceId != null && !collectDeviceId.equals(devImplRecordEntity.getCollectDeviceId()))) {
                    devImplRecordEntity.setCollectDeviceId(collectDeviceId);
                    updateflag = true;
                }
            }

            if (updateflag) devImplRecordDao.updateByPrimaryKey(devImplRecordEntity);
        }
    }


    @Scheduled(cron = "0 0 5 * * ?")
    @Async
    public void device2statis_collectDevice() throws Exception {
        if ("dev".equals(this.active)) return;
        statisDao.insert1();
    }
    @Scheduled(cron = "0 30 5 * * ?")
    @Async
    public void user2device_company() throws Exception {
        if ("dev".equals(this.active)) return;
        deviceDao.insert1();
    }


    @Scheduled(cron = "*/5 * 9-22 * * ?")
    @Async
    public void syncDtuData_5s() {
        if ("dev".equals(this.active)) return;
        (new Date()).getTime();


        List<DevIotDeviceEntity> dtus = new ArrayList<DevIotDeviceEntity>();
        Map<String, Object> criteriaMap = new HashMap<String, Object>();
        criteriaMap.put("startDate1", HzhrDateUtil.dateToStr(HzhrDateUtil.getDayBegin()));
        List<Map<String, Object>> iotdevices = this.smDeviceCustomDao.selectIotDevice1(criteriaMap);
        String dtuCategoryCode = this.devOptionsService.getCode("IOT_DEVICE_CATEGORY", "DTU");
        String gprsCategoryCode = this.devOptionsService.getCode("IOT_DEVICE_CATEGORY", "GPRS_IOT_GAS_METER");
        String ccrCategoryCode = this.devOptionsService.getCode("IOT_DEVICE_CATEGORY", "CONCENTRATOR");
        String pulseCategoryCode = this.devOptionsService.getCode("IOT_DEVICE_CATEGORY", "PULSE_READING");
        String iotPlatformCode = this.devOptionsService.getCode("IOT_PLATFORM_TYPE", "SELF_BUILD");

        List<DevIotDeviceTypeEntity> devIotDeviceTypeEntities = this.devIotDeviceTypeDao.selectByExample(null);
        Map<String, Integer> dtuIotDeviceTypes = new HashMap<String, Integer>();
        Map<String, Integer> gprsIotDeviceTypes = new HashMap<String, Integer>();
        Map<String, Integer> pulseIotDeviceTypes = new HashMap<String, Integer>();
        Map<String, Integer> ccrIotDeviceTypes = new HashMap<String, Integer>();

        if (devIotDeviceTypeEntities.size() > 0) {
            DevIotDeviceTypeEntity devIotDeviceTypeEntity = devIotDeviceTypeEntities.get(0);
            if (dtuCategoryCode.equals(devIotDeviceTypeEntity.getDeviceCategoryCode())) {
                dtuIotDeviceTypes.put(devIotDeviceTypeEntity.getOutId(), devIotDeviceTypeEntity.getId());
            }  if (gprsCategoryCode.equals(devIotDeviceTypeEntity.getDeviceCategoryCode())) {
                gprsIotDeviceTypes.put(devIotDeviceTypeEntity.getOutId(), devIotDeviceTypeEntity.getId());
            }  if (pulseCategoryCode.equals(devIotDeviceTypeEntity.getDeviceCategoryCode())) {
                pulseIotDeviceTypes.put(devIotDeviceTypeEntity.getOutId(), devIotDeviceTypeEntity.getId());
            }  if (ccrCategoryCode.equals(devIotDeviceTypeEntity.getDeviceCategoryCode())) {
                ccrIotDeviceTypes.put(devIotDeviceTypeEntity.getOutId(), devIotDeviceTypeEntity.getId());
            }
        }

        List<UsrDeptEntity> usrDeptEntities = this.usrDeptDao.selectByExample(null);
        Map<String, UsrDeptEntity> userDepts = new HashMap<String, UsrDeptEntity>();

        if (usrDeptEntities.size() > 0) {
            UsrDeptEntity userDeptEntity = usrDeptEntities.get(0);
            userDepts.put(userDeptEntity.getCode(), userDeptEntity);
        }


        List<UsrCompanyEntity> usrCompanyEntities = this.usrCompanyDao.selectByExample(null);
        Map<String, Integer> usrCompanys = new HashMap<String, Integer>();

        Iterator iterator1 = usrCompanyEntities.iterator();
        while (iterator1.hasNext()) {
            UsrCompanyEntity usrCompanyEntity = (UsrCompanyEntity)iterator1.next();
            usrCompanys.put(usrCompanyEntity.getOutId(), usrCompanyEntity.getId());
        }


        iterator1 = iotdevices.iterator();
        while (iterator1.hasNext()) {
            Map<String, Object> iotdevice = (Map)iterator1.next();
            try {
                String nodeId = HzhrTypeUtil.object2string(iotdevice.get("NODE_ID"));
                HzhrTypeUtil.object2string(iotdevice.get("EQ_ID"));
                String eqNo = HzhrTypeUtil.object2string(iotdevice.get("EQ_NO"));
                String des = HzhrTypeUtil.object2string(iotdevice.get("INSTALL_ADDR"));
                HzhrTypeUtil.object2string(iotdevice.get("MT_ID"));
                String dtutId = HzhrTypeUtil.object2string(iotdevice.get("DTUT_ID"));
                HzhrTypeUtil.object2string(iotdevice.get("CCT_ID"));
                String orgId = HzhrTypeUtil.object2string(iotdevice.get("ORG_ID"));
                HzhrTypeUtil.object2string(iotdevice.get("MPR_ID"));
                String dPrId = HzhrTypeUtil.object2string(iotdevice.get("DPR_ID"));
                HzhrTypeUtil.object2string(iotdevice.get("CPR_ID"));
                String deptCode = orgId.replace("0000", "9-01");
                String resourceCode = orgId.replace("0000", "01000901");

                if (dtutId != null) {
                    DevIotDeviceExample devIotDeviceExample = new DevIotDeviceExample();
                    devIotDeviceExample.createCriteria().andOutIdEqualTo(nodeId);
                    List<DevIotDeviceEntity> devIotDeviceEntities = this.devIotDeviceDao.selectByExample(devIotDeviceExample);

                    if (devIotDeviceEntities.size() == 0) {
                        DevIotDeviceEntity devIotDeviceEntity = new DevIotDeviceEntity();
                        devIotDeviceEntity.setOutId(nodeId);
                        devIotDeviceEntity.setCode(eqNo);
                        devIotDeviceEntity.setDes(des);
                        devIotDeviceEntity.setCategoryCode(dtuCategoryCode);
                        devIotDeviceEntity.setTypeId((Integer)dtuIotDeviceTypes.get(dtutId));

                        Integer iotCompanyId = (Integer)usrCompanys.get(dPrId);
                        devIotDeviceEntity.setCompanyId(Integer.valueOf((iotCompanyId != null) ? iotCompanyId.intValue() : 1));

                        UsrDeptEntity usrDeptEntity = (UsrDeptEntity)userDepts.get(deptCode);
                        if (usrDeptEntity != null) {
                            devIotDeviceEntity.setDeptId(usrDeptEntity.getId());
                        } else {
                            devIotDeviceEntity.setDeptId(Integer.valueOf(0));
                        }

                        devIotDeviceEntity.setGasCompanyId(Integer.valueOf(Integer.parseInt(this.companyId)));
                        devIotDeviceEntity.setIotPlatformCode(iotPlatformCode);
                        devIotDeviceEntity.setIotPlatformDeviceId(eqNo);
                        devIotDeviceEntity.setCreateTime(new Date());
                        devIotDeviceEntity.setCreateUserId(Integer.valueOf(0));
                        devIotDeviceEntity.setResourceCode(resourceCode);
                        devIotDeviceEntity.setIsValid(CommonOptions.YES_NO.YES);
                        devIotDeviceEntity.setState("1");
                        this.devIotDeviceDao.insert(devIotDeviceEntity);
                        dtus.add(devIotDeviceEntity); continue;
                    }
                    dtus.add((DevIotDeviceEntity)devIotDeviceEntities.get(0));
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }


        List<DevCollectDeviceEntity> flowMetres = new ArrayList<DevCollectDeviceEntity>();
        criteriaMap = new HashMap<String, Object>();
        criteriaMap.put("startDate", HzhrDateUtil.dateToStr(HzhrDateUtil.getDayBegin()));
        List<Map<String, Object>> collectDevices = this.smDeviceCustomDao.selectCollectDevice1(criteriaMap);

        List<DevCollectDeviceTypeEntity> devCollectDeviceTypeEntities = this.devCollectDeviceTypeDao.selectByExample(null);
        Map<String, Integer> collectDeviceTypes = new HashMap<String, Integer>();

        if (devCollectDeviceTypeEntities.size() > 0) {
            DevCollectDeviceTypeEntity devCollectDeviceTypeEntity = devCollectDeviceTypeEntities.get(0);
            collectDeviceTypes.put(devCollectDeviceTypeEntity.getOutId(), devCollectDeviceTypeEntity.getId());
        }


        String gprs = this.devOptionsService.getCode("COLLECT_DEVICE_CATEGORY", "GPRS_IOT_GAS_METER");
        String flowMeter = this.devOptionsService.getCode("COLLECT_DEVICE_CATEGORY", "FLOW_METER");
        String loraMeter = this.devOptionsService.getCode("COLLECT_DEVICE_CATEGORY", "LORA_METER");
        String bkMeter = this.devOptionsService.getCode("COLLECT_DEVICE_CATEGORY", "BK_METER");

        for ( Map<String, Object> collectDevice : collectDevices) {
            try {
                String meterId = HzhrTypeUtil.object2string(collectDevice.get("METER_ID"));
                String meterNo = HzhrTypeUtil.object2string(collectDevice.get("METER_NO"));
                String installAddr = HzhrTypeUtil.object2string(collectDevice.get("INSTALL_ADDR"));
                String remoteMeterId = HzhrTypeUtil.object2string(collectDevice.get("REMOTE_METER_ID"));
                String mtId = HzhrTypeUtil.object2string(collectDevice.get("MT_ID"));
                String orgId = HzhrTypeUtil.object2string(collectDevice.get("ORG_ID"));
                String yqdzId = HzhrTypeUtil.object2string(collectDevice.get("YQDZ_ID"));
                String pressureUnit = HzhrTypeUtil.object2string(collectDevice.get("PRESSURE_UNIT"));
                String parentNodeId = HzhrTypeUtil.object2string(collectDevice.get("NODE_ID"));
                String c = collectDevice.get("CREATE_TIME").toString();
                Date installTime = null;
                if (!StringUtils.isEmpty(c)) {
                    installTime = HzhrDateUtil.strToDate(c, "yyyy-MM-dd HH:mm:ss.ms");
                }

                String deptCode = orgId.replace("0000", "9-01");
                String resourceCode = orgId.replace("0000", "01000901");

                DevCollectDeviceExample devCollectDeviceExample = new DevCollectDeviceExample();
                devCollectDeviceExample.createCriteria().andOutIdEqualTo(meterId);
                List<DevCollectDeviceEntity> devCollectDataEntities = this.devCollectDeviceDao.selectByExample(devCollectDeviceExample);

                if (devCollectDataEntities.size() == 0) {
                    DevCollectDeviceEntity devCollectDeviceEntity = new DevCollectDeviceEntity();
                    devCollectDeviceEntity.setOutId(meterId);
                    devCollectDeviceEntity.setCode(meterNo);
                    devCollectDeviceEntity.setDes(installAddr);

                    if ("130".equals(remoteMeterId)) {
                        if (meterNo.startsWith("2066")) {
                            devCollectDeviceEntity.setCategoryCode(bkMeter);
                        } else {
                            devCollectDeviceEntity.setCategoryCode(gprs);
                        }
                    } else if ("132".equals(remoteMeterId)) {
                        devCollectDeviceEntity.setCategoryCode(loraMeter);
                    } else if ("134".equals(remoteMeterId)) {
                        devCollectDeviceEntity.setCategoryCode(flowMeter);
                    }

                    TollGasUserExample example = new TollGasUserExample();
                    example.createCriteria().andOutIdEqualTo(yqdzId);
                    List<TollGasUserEntity> tollGasUserEntities = this.tollGasUserDao.selectByExample(example);
                    if (tollGasUserEntities.size() > 0) {
                        TollGasUserEntity tollGasUserEntity = (TollGasUserEntity)tollGasUserEntities.get(0);
                        devCollectDeviceEntity.setGasUserId(tollGasUserEntity.getId());
                        devCollectDeviceEntity.setGasUserCode(tollGasUserEntity.getCode());
                        devCollectDeviceEntity.setGasUserAddress(tollGasUserEntity.getAddress());
                        devCollectDeviceEntity.setGasUserName(tollGasUserEntity.getName());
                    } else {
                        String resident = this.tollOptionsService.getCode("GAS_USER_TYPE", "RESIDENTIAL_USER");
                        String commercial = this.tollOptionsService.getCode("GAS_USER_TYPE", "COMMERCIAL_USER");


                        Map<String, Object> query = new HashMap<String, Object>();
                        query.put("meterId", meterId);
                        Map<String, Object> gasUser = this.smGasUserCustomDao.selectGasUser1(query);
                        String yqdzId1 = HzhrTypeUtil.object2string(gasUser.get("YQDZ_ID"));
                        String yqdzYqzh = HzhrTypeUtil.object2string(gasUser.get("YQDZ_YQZH"));
                        String yqdzHzMc = HzhrTypeUtil.object2string(gasUser.get("YQDZ_HZ_MC"));
                        String yqdzSm = HzhrTypeUtil.object2string(gasUser.get("YQDZ_SM"));
                        String yqdzKhLx = HzhrTypeUtil.object2string(gasUser.get("YQDZ_KH_LX"));
                        String orgId1 = HzhrTypeUtil.object2string(gasUser.get("ORG_ID"));

                        String deptCode1 = orgId1.replace("0000", "9-01");
                        String resourceCode1 = orgId1.replace("0000", "01000901");

                        TollGasUserExample tollGasUserExample = new TollGasUserExample();
                        tollGasUserExample.createCriteria().andOutIdEqualTo(yqdzId);
                        List<TollGasUserEntity> tollGasUserEntities1 = this.tollGasUserDao.selectByExample(tollGasUserExample);

                        if (tollGasUserEntities1.size() == 0) {
                            TollGasUserEntity tollGasUserEntity = new TollGasUserEntity();
                            tollGasUserEntity.setOutId(yqdzId1);
                            tollGasUserEntity.setCode(yqdzYqzh);
                            tollGasUserEntity.setName((yqdzHzMc != null) ? yqdzHzMc : "未知");
                            tollGasUserEntity.setAddress(yqdzSm);
                            if ("1".equals(yqdzKhLx)) {
                                tollGasUserEntity.setTypeCode(commercial);
                            } else if ("2".equals(yqdzKhLx)) {
                                tollGasUserEntity.setTypeCode(resident);
                            } else {
                                tollGasUserEntity.setTypeCode("0");
                            }
                            tollGasUserEntity.setCompanyId(Integer.valueOf(Integer.parseInt(this.companyId)));

                            UsrDeptExample usrDeptExample = new UsrDeptExample();
                            usrDeptExample.createCriteria().andCodeEqualTo(deptCode1);
                            List<UsrDeptEntity> usrDeptEntities1 = this.usrDeptDao.selectByExample(usrDeptExample);
                            if (usrDeptEntities1.size() > 0) {
                                UsrDeptEntity usrDeptEntity = (UsrDeptEntity)usrDeptEntities1.get(0);
                                tollGasUserEntity.setDeptId(usrDeptEntity.getId());
                            } else {
                                tollGasUserEntity.setDeptId(Integer.valueOf(0));
                            }

                            tollGasUserEntity.setCreateTime(new Date());
                            tollGasUserEntity.setCreateUserId(Integer.valueOf(0));
                            tollGasUserEntity.setResourceCode(resourceCode1);
                            tollGasUserEntity.setIsValid(CommonOptions.YES_NO.YES);
                            tollGasUserEntity.setState("1");
                            this.tollGasUserDao.insert(tollGasUserEntity);

                            devCollectDeviceEntity.setGasUserId(tollGasUserEntity.getId());
                            devCollectDeviceEntity.setGasUserCode(tollGasUserEntity.getCode());
                            devCollectDeviceEntity.setGasUserAddress(tollGasUserEntity.getAddress());
                            devCollectDeviceEntity.setGasUserName(tollGasUserEntity.getName());
                        }
                    }


                    Integer typeId = (Integer)collectDeviceTypes.get(mtId);
                    if (typeId != null) {
                        devCollectDeviceEntity.setTypeId(typeId);
                    } else {
                        devCollectDeviceEntity.setTypeId(Integer.valueOf(0));
                    }


                    Iterator iterator = dtus.iterator();
                    while (iterator.hasNext()) { DevIotDeviceEntity dtu = (DevIotDeviceEntity)iterator.next();
                        if (parentNodeId != null && parentNodeId.equals(dtu.getOutId())) {
                            devCollectDeviceEntity.setIotDeviceId(dtu.getId());
                            break;
                        }
                    }

                    UsrDeptEntity usrDeptEntity = (UsrDeptEntity)userDepts.get(deptCode);
                    if (usrDeptEntity != null) {
                        devCollectDeviceEntity.setDeptId(usrDeptEntity.getId());
                        devCollectDeviceEntity.setDeptCode(usrDeptEntity.getCode());
                    } else {
                        devCollectDeviceEntity.setDeptId(Integer.valueOf(0));
                    }

                    if ("1".equals(pressureUnit)) {
                        devCollectDeviceEntity.setPressureUnit("3");
                    } else if ("2".equals(pressureUnit)) {
                        devCollectDeviceEntity.setPressureUnit("2");
                    } else if ("3".equals(pressureUnit)) {
                        devCollectDeviceEntity.setPressureUnit("1");
                    }

                    devCollectDeviceEntity.setCompanyId(Integer.valueOf(Integer.parseInt(this.companyId)));
                    devCollectDeviceEntity.setInstallTime(installTime);
                    devCollectDeviceEntity.setCreateTime(new Date());
                    devCollectDeviceEntity.setCreateUserId(Integer.valueOf(0));
                    devCollectDeviceEntity.setResourceCode(resourceCode);
                    devCollectDeviceEntity.setIsValid(CommonOptions.YES_NO.YES);
                    devCollectDeviceEntity.setState("1");
                    this.devCollectDeviceDao.insert(devCollectDeviceEntity);
                    flowMetres.add(devCollectDeviceEntity);
                }
            }
            catch (Exception e) {
                e.printStackTrace();
            }
        }



        String open = this.devOptionsService.getCode("VALVE_STATUS", "OPEN");
        String close = this.devOptionsService.getCode("VALVE_STATUS", "CLOSE");
        this.devOptionsService.getCode("VALVE_STATUS", "ERROR");
        List<DevCollectDataEntity> addList = new ArrayList<DevCollectDataEntity>();


        Iterator iterator2 = flowMetres.iterator();
        while (iterator2.hasNext()) {
            DevCollectDeviceEntity flowMeter1 = (DevCollectDeviceEntity)iterator2.next();
            criteriaMap = new HashMap<String, Object>();
            criteriaMap.put("startDate", HzhrDateUtil.dateToStr(HzhrDateUtil.getDayBegin()));
            criteriaMap.put("eqId", flowMeter1.getOutId());
            List<Map<String, Object>> collecingDatas = this.smCollectDataCustomDao.selectCollectData1(criteriaMap);

            Iterator iterator = collecingDatas.iterator();
            while (iterator.hasNext()) {
                Map<String, Object> collectingData = (Map)iterator.next();
                HzhrTypeUtil.object2string(collectingData.get("CD_ID"));
                String nodeId = HzhrTypeUtil.object2string(collectingData.get("NODE_ID"));
                if (nodeId == null)
                    continue;
                String eqId = HzhrTypeUtil.object2string(collectingData.get("EQ_ID"));
                if (eqId == null)
                    continue;
                String connectionPointNode = HzhrTypeUtil.object2string(collectingData.get("CONNECTION_POINT_NODE"));
                String cdTime = HzhrTypeUtil.object2string(collectingData.get("CD_TIME"));
                if (cdTime == null)
                    continue;
                cdTime = cdTime.substring(0, cdTime.indexOf("."));
                Date currentTime = HzhrDateUtil.strToDate(cdTime);
                String currentValue = HzhrTypeUtil.object2string(collectingData.get("CURRENT_VALUE"));
                if (currentValue == null)
                    continue;
                String signal = HzhrTypeUtil.object2string(collectingData.get("SIGNAL"));
                HzhrTypeUtil.object2string(collectingData.get("POWERTYPE"));
                String voltage = HzhrTypeUtil.object2string(collectingData.get("VOLTAGE"));
                String tmp = HzhrTypeUtil.object2string(collectingData.get("TMP"));
                String pressure = HzhrTypeUtil.object2string(collectingData.get("PRESSURE"));
                String temperature = HzhrTypeUtil.object2string(collectingData.get("TEMPERATURE"));
                String standardFlow = HzhrTypeUtil.object2string(collectingData.get("STANDARD_FLOW"));
                String workFlow = HzhrTypeUtil.object2string(collectingData.get("WORKING_FLOW"));
                String standardFlowSum = HzhrTypeUtil.object2string(collectingData.get("STANDARD_FLOW_SUM"));
                String workFlowSum = HzhrTypeUtil.object2string(collectingData.get("WORKING_FLOW_SUM"));
                String standardCorrect = HzhrTypeUtil.object2string(collectingData.get("STANDARD_CORRECT"));
                String valveStateId = HzhrTypeUtil.object2string(collectingData.get("VALVE_STATE_ID"));

                DevCollectDataExample devCollectDataExample = new DevCollectDataExample();
                devCollectDataExample.createCriteria().andCollectDeviceIdEqualTo(flowMeter1.getId()).andCurrentTmEqualTo(currentTime);
                int count = this.devCollectDataDao.countByExample(devCollectDataExample);

                if (count == 0) {
                    DevCollectDataEntity devCollectDataEntity = new DevCollectDataEntity();
                    devCollectDataEntity.setTemperature(HzhrTypeUtil.string2float(temperature));
                    devCollectDataEntity.setCollectDeviceId(flowMeter1.getId());

                    Iterator iterator3 = dtus.iterator();
                    while (iterator3.hasNext()) {
                        DevIotDeviceEntity dtu = (DevIotDeviceEntity)iterator3.next();
                        if (connectionPointNode != null && connectionPointNode.equals(dtu.getOutId())) {
                            devCollectDataEntity.setIotDeviceId(dtu.getId());
                            break;
                        }
                    }

                    devCollectDataEntity.setCurrentTm(currentTime);
                    devCollectDataEntity.setCurrentValue(Double.valueOf(Double.parseDouble(currentValue)));
                    devCollectDataEntity.setStaTotalFlow(HzhrTypeUtil.string2double(standardFlowSum));
                    devCollectDataEntity.setWorkTotalFlow(HzhrTypeUtil.string2double(workFlowSum));
                    devCollectDataEntity.setDisTotalFlow(HzhrTypeUtil.string2double(standardCorrect));
                    devCollectDataEntity.setStaFlowRate(HzhrTypeUtil.string2double(standardFlow));
                    devCollectDataEntity.setWorkFlowRate(HzhrTypeUtil.string2double(workFlow));
                    devCollectDataEntity.setPressure(HzhrTypeUtil.string2double(pressure));
                    devCollectDataEntity.setTemperature(HzhrTypeUtil.string2float(tmp));
                    if ("1".equals(valveStateId)) {
                        devCollectDataEntity.setValveStatusCode(open);
                    } else if ("0".equals(valveStateId)) {
                        devCollectDataEntity.setValveStatusCode(close);
                    }
                    devCollectDataEntity.setSignalStrength(HzhrTypeUtil.string2integer(signal));
                    devCollectDataEntity.setCellVoltage(HzhrTypeUtil.string2float(voltage));
                    devCollectDataEntity.setCreateTime(new Date());
                    devCollectDataEntity.setIsValid(CommonOptions.YES_NO.YES);
                    devCollectDataEntity.setState("1");
                    addList.add(devCollectDataEntity);
                    if (addList.size() > 5000) {
                        this.devCollectDataCustomDao.insertBatch(addList);
                        addList = new ArrayList<DevCollectDataEntity>();
                    }
                }
            }
        }

        int addListSize = addList.size();
        if (addListSize > 0)
            this.devCollectDataCustomDao.insertBatch(addList);
    }
    @Scheduled(cron = "*/10 * 9-22 * * ?")
    @Async
    public void syncCollectingData_5s() throws Exception {
        if ("dev".equals(this.active)) return;
        int syncCount = 0;
        long start = new Date().getTime();

        Date date1 = HzhrDateUtil.getDayBegin();
        Date date2 = HzhrDateUtil.addDay(date1, 1);

        //同步数据
        List<Future<Integer>> lstFuture = new ArrayList<Future<Integer>>();// 存放所有的线程，用于获取结果
        Future<Integer> result = collectingDataService.syncCollectingData1(date1, date2);
        lstFuture.add(result);
        for (Future<Integer> future : lstFuture) {// 获取值。get是阻塞式，等待当前线程完成才返回值
            syncCount += future.get();
        }

        long end = new Date().getTime();
        if (end - start >= 8000) {
            logger.info("同步采集数据结束: " + (end - start) / 1000 + "s");
            logger.info("同步时间: " + (end - start) / 1000 + "s");
            logger.info("同步数量: " + syncCount + "条");
        }
    }

    //同步采集设备状态信息
    @Scheduled(cron = "0 0 6 * * ?")
    @Async
    public void syncCollectDeviceStatusInfo() {
        if ("dev".equals(this.active)) return;
        collectDeviceService.syncCollectDeviceStatusInfo();
    }
    //同步燃气用户用气量及设备数量
    @Scheduled(cron = "0 0 6 * * ?")
    @Async
    public void syncGasUserGasConsumeAndDeviceCount() {
        if ("dev".equals(this.active)) return;
        gasUserService.syncGasUserGasConsumeAndDeviceCount();
    }


    //同步统计信息
    @Scheduled(cron = "0 30 6 * * ?")
    @Async
    public void syncDeviceStatis_day() throws Exception {
        if ("dev".equals(this.active)) return;
        long start = new Date().getTime();

        Map<String, Integer> logMap = new HashMap<>();
        logMap.put("deviceDailyGasConsumeUpdateCount", 0);
        logMap.put("deviceDailyGasConsumeInsertCount", 0);
        logMap.put("deviceMonthlyGasConsumeUpdateCount", 0);
        logMap.put("deviceMonthlyGasConsumeInsertCount", 0);

        int day = 1;

        //查询出采集设备
        List<DevCollectDeviceEntity> devCollectDeviceEntities = devCollectDeviceDao.selectByExample(new DevCollectDeviceExample());

        //同步数据
        List<Future<Map<String, Integer>>> lstFuture = new ArrayList<Future<Map<String, Integer>>>();// 存放所有的线程，用于获取结果
        for (int i = 1; i <= 10; i++) {
            Future<Map<String, Integer>> result = statisService.syncDeviceStatis(i, day, devCollectDeviceEntities);
            lstFuture.add(result);
        }

        for (Future<Map<String, Integer>> future : lstFuture) {// 获取值。get是阻塞式，等待当前线程完成才返回值
            int deviceDailyGasConsumeUpdateCount = logMap.get("deviceDailyGasConsumeUpdateCount");
            deviceDailyGasConsumeUpdateCount += future.get().get("deviceDailyGasConsumeUpdateCount");
            logMap.put("deviceDailyGasConsumeUpdateCount", deviceDailyGasConsumeUpdateCount);

            int deviceDailyGasConsumeInsertCount = logMap.get("deviceDailyGasConsumeInsertCount");
            deviceDailyGasConsumeInsertCount += future.get().get("deviceDailyGasConsumeInsertCount");
            logMap.put("deviceDailyGasConsumeInsertCount", deviceDailyGasConsumeInsertCount);

            int deviceMonthlyGasConsumeUpdateCount = logMap.get("deviceMonthlyGasConsumeUpdateCount");
            deviceMonthlyGasConsumeUpdateCount += future.get().get("deviceMonthlyGasConsumeUpdateCount");
            logMap.put("deviceMonthlyGasConsumeUpdateCount", deviceMonthlyGasConsumeUpdateCount);

            int deviceMonthlyGasConsumeInsertCount = logMap.get("deviceMonthlyGasConsumeInsertCount");
            deviceMonthlyGasConsumeInsertCount += future.get().get("deviceMonthlyGasConsumeInsertCount");
            logMap.put("deviceMonthlyGasConsumeInsertCount", deviceMonthlyGasConsumeInsertCount);
        }

        long end = new Date().getTime();
        logger.info("同步设备统计结束: ");
        logger.info("同步时间: " + (end - start) / 1000 + "s");
        logger.info("更新日统计数量: " + logMap.get("deviceDailyGasConsumeUpdateCount") + "条");
        logger.info("新增日统计数量: " + logMap.get("deviceDailyGasConsumeInsertCount") + "条");
        logger.info("更新月统计数量: " + logMap.get("deviceMonthlyGasConsumeUpdateCount") + "条");
        logger.info("新增月统计数量: " + logMap.get("deviceMonthlyGasConsumeInsertCount") + "条");
    }
    @Scheduled(cron = "0 0 7,13 * * ?")
    @Async
    public void syncDeviceStatisException_day() throws Exception {
        if ("dev".equals(this.active)) return;
        long start = new Date().getTime();

        List<Integer> ids = deviceDao.select15();
        for (Integer id :
                ids) {
            while (true) {
                Map<String, Object> map = statisDao.select3(id);
                if (map == null) break;
                Integer count = HzhrTypeUtil.object2integer(map.get("C"));
                Double per = HzhrTypeUtil.object2double(map.get("P"));
                Double max = HzhrTypeUtil.object2double(map.get("M"));
                Double sub = HzhrTypeUtil.object2double(map.get("S"));

                boolean updateFlag = false;
                if (per != null && count > 2 && max > 10) {
                    if (per >= 50) {
                        int changeCount = statisDao.update1(id, HzhrDateUtil.dateToStr(HzhrDateUtil.addDay(HzhrDateUtil.getDayBegin(), -1)), null);
                        if (changeCount > 0) {
                            updateFlag = true;
                        }
                    }
                    if (!updateFlag && per > 20 && sub > 500) {
                        int changeCount = statisDao.update1(id, HzhrDateUtil.dateToStr(HzhrDateUtil.addDay(HzhrDateUtil.getDayBegin(), -1)), null);
                        if (changeCount > 0) {
                            updateFlag = true;
                        }
                    }
                    if (!updateFlag && count > 10 && per >= 5 && max >= 100) {
                        int changeCount = statisDao.update1(id, HzhrDateUtil.dateToStr(HzhrDateUtil.addDay(HzhrDateUtil.getDayBegin(), -1)), null);
                        if (changeCount > 0) {
                            updateFlag = true;
                        }
                    }
                }

                if (!updateFlag) break;
            }
        }

        long end = new Date().getTime();
        logger.info("同步设备统计数据异常结束: ");
        logger.info("同步时间: " + (end - start) / 1000 + "s");
    }
    @Scheduled(cron = "0 30 7 * * ?")
    @Async
    public void syncGasUserStatis_day() throws Exception {
        if ("dev".equals(this.active)) return;
        long start = new Date().getTime();

        Map<String, Integer> logMap = new HashMap<>();
        logMap.put("gasUserDailyGasConsumeUpdateCount", 0);
        logMap.put("gasUserDailyGasConsumeInsertCount", 0);
        logMap.put("gasUserMonthlyGasConsumeUpdateCount", 0);
        logMap.put("gasUserMonthlyGasConsumeInsertCount", 0);

        int day = 1;

        //查询出燃气用户
        List<TollGasUserEntity> tollGasUserEntities = tollGasUserDao.selectByExample(null);

        //同步数据
        List<Future<Map<String, Integer>>> lstFuture = new ArrayList<Future<Map<String, Integer>>>();// 存放所有的线程，用于获取结果
        for (int i = 1; i <= 10; i++) {
            Future<Map<String, Integer>> result = statisService.syncGasUserStatis(i, day, tollGasUserEntities);
            lstFuture.add(result);
        }

        for (Future<Map<String, Integer>> future : lstFuture) {// 获取值。get是阻塞式，等待当前线程完成才返回值
            int gasUserDailyGasConsumeUpdateCount = logMap.get("gasUserDailyGasConsumeUpdateCount");
            gasUserDailyGasConsumeUpdateCount += future.get().get("gasUserDailyGasConsumeUpdateCount");
            logMap.put("gasUserDailyGasConsumeUpdateCount", gasUserDailyGasConsumeUpdateCount);

            int gasUserDailyGasConsumeInsertCount = logMap.get("gasUserDailyGasConsumeInsertCount");
            gasUserDailyGasConsumeInsertCount += future.get().get("gasUserDailyGasConsumeInsertCount");
            logMap.put("gasUserDailyGasConsumeInsertCount", gasUserDailyGasConsumeInsertCount);

            int gasUserMonthlyGasConsumeUpdateCount = logMap.get("gasUserMonthlyGasConsumeUpdateCount");
            gasUserMonthlyGasConsumeUpdateCount += future.get().get("gasUserMonthlyGasConsumeUpdateCount");
            logMap.put("gasUserMonthlyGasConsumeUpdateCount", gasUserMonthlyGasConsumeUpdateCount);

            int gasUserMonthlyGasConsumeInsertCount = logMap.get("gasUserMonthlyGasConsumeInsertCount");
            gasUserMonthlyGasConsumeInsertCount += future.get().get("gasUserMonthlyGasConsumeInsertCount");
            logMap.put("gasUserMonthlyGasConsumeInsertCount", gasUserMonthlyGasConsumeInsertCount);
        }

        long end = new Date().getTime();
        logger.info("同步燃气用户统计结束: ");
        logger.info("同步时间: " + (end - start) / 1000 + "s");
        logger.info("更新日统计数量: " + logMap.get("gasUserDailyGasConsumeUpdateCount") + "条");
        logger.info("新增日统计数量: " + logMap.get("gasUserDailyGasConsumeInsertCount") + "条");
        logger.info("更新月统计数量: " + logMap.get("gasUserMonthlyGasConsumeUpdateCount") + "条");
        logger.info("新增月统计数量: " + logMap.get("gasUserMonthlyGasConsumeInsertCount") + "条");
    }
    @Scheduled(cron = "0 40 7,8,12 * * ?")
    @Async
    public void syncDeptStatis_day() throws Exception {
        if ("dev".equals(this.active)) return;
        long start = new Date().getTime();

        Map<String, Integer> logMap = new HashMap<>();
        logMap.put("deptDailyGasConsumeUpdateCount", 0);
        logMap.put("deptDailyGasConsumeInsertCount", 0);
        logMap.put("deptMonthlyGasConsumeUpdateCount", 0);
        logMap.put("deptMonthlyGasConsumeInsertCount", 0);

        int day = 1;

        //查询出燃气用户
        List<UsrDeptEntity> usrDeptEntities = usrDeptDao.selectByExample(null);

        //同步数据
        List<Future<Map<String, Integer>>> lstFuture = new ArrayList<Future<Map<String, Integer>>>();// 存放所有的线程，用于获取结果
        Future<Map<String, Integer>> result = statisService.syncDeptStatis(day, usrDeptEntities);
        lstFuture.add(result);

        for (Future<Map<String, Integer>> future : lstFuture) {// 获取值。get是阻塞式，等待当前线程完成才返回值
            int deptDailyGasConsumeUpdateCount = logMap.get("deptDailyGasConsumeUpdateCount");
            deptDailyGasConsumeUpdateCount += future.get().get("deptDailyGasConsumeUpdateCount");
            logMap.put("deptDailyGasConsumeUpdateCount", deptDailyGasConsumeUpdateCount);

            int deptDailyGasConsumeInsertCount = logMap.get("deptDailyGasConsumeInsertCount");
            deptDailyGasConsumeInsertCount += future.get().get("deptDailyGasConsumeInsertCount");
            logMap.put("deptDailyGasConsumeInsertCount", deptDailyGasConsumeInsertCount);

            int deptMonthlyGasConsumeUpdateCount = logMap.get("deptMonthlyGasConsumeUpdateCount");
            deptMonthlyGasConsumeUpdateCount += future.get().get("deptMonthlyGasConsumeUpdateCount");
            logMap.put("deptMonthlyGasConsumeUpdateCount", deptMonthlyGasConsumeUpdateCount);

            int deptMonthlyGasConsumeInsertCount = logMap.get("deptMonthlyGasConsumeInsertCount");
            deptMonthlyGasConsumeInsertCount += future.get().get("deptMonthlyGasConsumeInsertCount");
            logMap.put("deptMonthlyGasConsumeInsertCount", deptMonthlyGasConsumeInsertCount);
        }

        long end = new Date().getTime();
        logger.info("同步部门统计结束: ");
        logger.info("同步时间: " + (end - start) / 1000 + "s");
        logger.info("更新日统计数量: " + logMap.get("deptDailyGasConsumeUpdateCount") + "条");
        logger.info("新增日统计数量: " + logMap.get("deptDailyGasConsumeInsertCount") + "条");
        logger.info("更新月统计数量: " + logMap.get("deptMonthlyGasConsumeUpdateCount") + "条");
        logger.info("新增月统计数量: " + logMap.get("deptMonthlyGasConsumeInsertCount") + "条");
    }
    @Scheduled(cron = "0 10 8,12 * * ?")
    @Async
    public void syncDeviceDataException() throws Exception {
        if ("dev".equals(this.active)) return;
        long start = (new Date()).getTime();

        Map<String, Integer> logMap = new HashMap<String, Integer>();
        logMap.put("wscCount", Integer.valueOf(0));
        logMap.put("wyqCount", Integer.valueOf(0));


        List<Map<String, Object>> devices = this.devCollectDeviceCustomDao.select1();


        List<Map<String, Object>> depts = this.userCustomDao.select1();
        List<Map<String, Object>> companys = this.userCustomDao.select2();

        Iterator iterator = devices.iterator();
        while (iterator.hasNext()) {
            Map<String, Object> device = (Map)iterator.next();
            Integer COLLECT_DEVICE_DEPT_ID = HzhrTypeUtil.object2integer(device.get("COLLECT_DEVICE_DEPT_ID"));
            Integer IOT_DEVICE_COMPANY_ID = HzhrTypeUtil.object2integer(device.get("IOT_DEVICE_COMPANY_ID"));


            Iterator iterator1 = depts.iterator(); while (iterator1.hasNext()) { Map<String, Object> dept = (Map)iterator1.next();
                Integer id = HzhrTypeUtil.object2integer(dept.get("ID"));
                String name = HzhrTypeUtil.object2string(dept.get("NAME"));
                if (id.equals(COLLECT_DEVICE_DEPT_ID)) {
                    device.put("COLLECT_DEVICE_DEPT_NAME", name);

                    break;
                }  }


            iterator1 = companys.iterator(); while (iterator1.hasNext()) { Map<String, Object> company = (Map)iterator1.next();
                Integer id = HzhrTypeUtil.object2integer(company.get("ID"));
                String name = HzhrTypeUtil.object2string(company.get("NAME"));
                if (id.equals(IOT_DEVICE_COMPANY_ID)) {
                    device.put("IOT_DEVICE_COMPANY_NAME", name);

                    break;
                }
            }
        }


        List<Future<Map<String, Integer>>> lstFuture = new ArrayList<Future<Map<String, Integer>>>();
        Future<Map<String, Integer>> result = this.statisService.syncDeviceDataException(devices);
        lstFuture.add(result);

        for (Future<Map<String, Integer>> future : lstFuture) {
            int wscCount = ((Integer)logMap.get("wscCount")).intValue();
            wscCount += ((Integer)((Map)future.get()).get("wscCount")).intValue();
            logMap.put("wscCount", Integer.valueOf(wscCount));

            int wyqCount = ((Integer)logMap.get("wyqCount")).intValue();
            wyqCount += ((Integer)((Map)future.get()).get("wyqCount")).intValue();
            logMap.put("wyqCount", Integer.valueOf(wyqCount));
        }

        long end = (new Date()).getTime();
        logger.info("同步设备数据异常统计结束: ");
        logger.info("同步时间: " + (end - start) / 1000 + "s");
        logger.info("未上传: " + logMap.get("wscCount") + "条");
        logger.info("未用气: " + logMap.get("wyqCount") + "条");
    }
    @Scheduled(cron = "0 0 8,12 * * ?")
    @Async
    public void syncDeviceStatis_day_onlyDay() throws Exception {
        if ("dev".equals(this.active)) return;
        long start = (new Date()).getTime();

        Map<String, Integer> logMap = new HashMap<String, Integer>();
        logMap.put("deviceDailyGasConsumeUpdateCount", Integer.valueOf(0));
        logMap.put("deviceDailyGasConsumeInsertCount", Integer.valueOf(0));

        int day = 1;


        List<DevCollectDeviceEntityDto> devCollectDeviceEntities = deviceDao.select7();


        List<Integer> collectDeviceIds = this.statisDao.select1(HzhrDateUtil.dateToStr(HzhrDateUtil.addDay(HzhrDateUtil.getDayBegin(), -1)));
        List<DevCollectDeviceEntityDto> devCollectDeviceEntities1 = new ArrayList<>();

        for (DevCollectDeviceEntityDto devCollectDeviceEntity:
        devCollectDeviceEntities) {
            Integer collectDeviceId = devCollectDeviceEntity.getId();
            if (!collectDeviceIds.contains(collectDeviceId)) {
                devCollectDeviceEntities1.add(devCollectDeviceEntity);
            }
        }

        List<Future<Map<String, Integer>>> lstFuture = new ArrayList<>();
        for (int i = 1; i <= 10; i++) {
            Future<Map<String, Integer>> result = this.statisService.syncDeviceStatis_onlyDay(i, Integer.valueOf(day), devCollectDeviceEntities1);
            lstFuture.add(result);
        }

        for (Future<Map<String, Integer>> future : lstFuture) {
            int deviceDailyGasConsumeUpdateCount = ((Integer)logMap.get("deviceDailyGasConsumeUpdateCount")).intValue();
            deviceDailyGasConsumeUpdateCount += ((Integer)((Map)future.get()).get("deviceDailyGasConsumeUpdateCount")).intValue();
            logMap.put("deviceDailyGasConsumeUpdateCount", Integer.valueOf(deviceDailyGasConsumeUpdateCount));

            int deviceDailyGasConsumeInsertCount = ((Integer)logMap.get("deviceDailyGasConsumeInsertCount")).intValue();
            deviceDailyGasConsumeInsertCount += ((Integer)((Map)future.get()).get("deviceDailyGasConsumeInsertCount")).intValue();
            logMap.put("deviceDailyGasConsumeInsertCount", Integer.valueOf(deviceDailyGasConsumeInsertCount));
        }

        long end = new Date().getTime();
        logger.info("同步设备统计结束: ");
        logger.info("同步时间: " + (end - start) / 1000 + "s");
        logger.info("更新日统计数量: " + logMap.get("deviceDailyGasConsumeUpdateCount") + "条");
        logger.info("新增日统计数量: " + logMap.get("deviceDailyGasConsumeInsertCount") + "条");
    }
    @Scheduled(cron = "0 20 8,12 * * ?")
    @Async
    public void syncGasUserStatis_day_onlyDay() throws Exception {
        if ("dev".equals(this.active)) return;
        long start = (new Date()).getTime();

        Map<String, Integer> logMap = new HashMap<String, Integer>();
        logMap.put("gasUserDailyGasConsumeUpdateCount", Integer.valueOf(0));
        logMap.put("gasUserDailyGasConsumeInsertCount", Integer.valueOf(0));

        int day = 1;


        List<TollGasUserEntityDto> tollGasUserEntities = tollGasUserCustomDao.select2();


        List<Integer> gasUserIds = this.statisDao.select2(HzhrDateUtil.dateToStr(HzhrDateUtil.addDay(HzhrDateUtil.getDayBegin(), -1)));
        List<TollGasUserEntityDto> tollGasUserEntities1 = new ArrayList<>();

        for (TollGasUserEntityDto tollGasUserEntity :
        tollGasUserEntities) {
            Integer gasUserId = tollGasUserEntity.getId();
            if (!gasUserIds.contains(gasUserId)) {
                tollGasUserEntities1.add(tollGasUserEntity);
            }
        }



        List<Future<Map<String, Integer>>> lstFuture = new ArrayList<Future<Map<String, Integer>>>();
        for (int i = 1; i <= 10; i++) {
            Future<Map<String, Integer>> result = this.statisService.syncGasUserStatis_onlyDay(i, Integer.valueOf(day), tollGasUserEntities1);
            lstFuture.add(result);
        }

        for (Future<Map<String, Integer>> future : lstFuture) {
            int gasUserDailyGasConsumeUpdateCount = ((Integer)logMap.get("gasUserDailyGasConsumeUpdateCount")).intValue();
            gasUserDailyGasConsumeUpdateCount += ((Integer)((Map)future.get()).get("gasUserDailyGasConsumeUpdateCount")).intValue();
            logMap.put("gasUserDailyGasConsumeUpdateCount", Integer.valueOf(gasUserDailyGasConsumeUpdateCount));

            int gasUserDailyGasConsumeInsertCount = ((Integer)logMap.get("gasUserDailyGasConsumeInsertCount")).intValue();
            gasUserDailyGasConsumeInsertCount += ((Integer)((Map)future.get()).get("gasUserDailyGasConsumeInsertCount")).intValue();
            logMap.put("gasUserDailyGasConsumeInsertCount", Integer.valueOf(gasUserDailyGasConsumeInsertCount));
        }

        long end = new Date().getTime();
        logger.info("同步燃气用户统计结束: ");
        logger.info("同步时间: " + (end - start) / 1000 + "s");
        logger.info("更新日统计数量: " + logMap.get("gasUserDailyGasConsumeUpdateCount") + "条");
        logger.info("新增日统计数量: " + logMap.get("gasUserDailyGasConsumeInsertCount") + "条");
    }


    //同步数据到采集平台
    //@Scheduled(cron = "0 0 9 * * ?")
    @Async
    public void sm_syncCollectingData() throws Exception {
        if ("dev".equals(this.active)) return;
        String date = HzhrDateUtil.dateToStr(HzhrDateUtil.addDay(new Date(), -1), "yyyy-MM-dd") + " 00:00:00";
        List<Map<String, Object>> collectDatas = deviceDao.select6(date);
        for (Map<String, Object> collectData :
                collectDatas) {
            String code = HzhrTypeUtil.object2string(collectData.get("CODE"));
            CustomEntity1 device = smDao.select2(code);
            if (device == null) continue;
            device.setCdTime(collectData.get("CURRENT_TM"));
            device.setCurrentValue(HzhrTypeUtil.object2string(collectData.get("CURRENT_VALUE")));
            Random random = new Random();
            Long id = random.nextLong();
            if (id < 0) {
                id = id * -1;
            }
            String ids = id.toString();
            if (ids.length() > 13) {
                ids = ids.substring(0, 13);
            }
            device.setCdId("N" + ids);
            smDao.insert1(device);
        }
    }

    @Scheduled(cron = "0 0 16 * * ?")
    @Async
    public void log2log_log() throws Exception {
        if ("dev".equals(this.active)) return;
        String dateStr = HzhrDateUtil.dateToStr(HzhrDateUtil.addDay(new Date(), 1), "yyyyMMdd");
        logDao.insert1(dateStr);
    }
}
